<?php

namespace Theatre\Client;

class User extends \Theatre\Controller {
	function index() {
		if ($this->userExists()) {
			$this->redirect('/booking');

			return;
		}

		$this->redirect('/user/login');
	}

	/**
	 * Login the user based on username and password
	 */
	public function login() {
		// nothing to see here if already authed
		if ($this->userExists()) {
			$this->redirect('/booking');

			return;
		}

		// nothing posted, stop right here	
		if (empty($_POST)) {
			return;
		}

		if (empty($this->params['username'])) {
			$this->set(array(
				'status'  => 'error',
				'field'   => 'username',
				'message' => 'Fill in the username'
			));

			return;
		}

		if (empty($this->params['password'])) {
			$this->set(array(
				'status'  => 'error',
				'field'   => 'password',
				'message' => 'Fill in the password'
			));

			return;
		}

		$authed = $this->authenticate(array(
			'username' => $this->params['username'],
			'password' => $this->params['password']
		));

		if (!$authed) {
			$this->set(array(
				'status'  => 'error',
				'message' => 'Invalid username or password'
			));

			return;
		}

		$this->set(array(
			'status'  => 'success'
		));

		$this->redirect('/booking');
	}


	/**
	 * Logout user
	 */
	public function logout() {
		$this->_logout();

		$this->redirect('/user/login');
	}


	/**
	 * Before render callback
	 */
	protected function beforeRender() {
		parent::beforeRender();

		$this->set(array('loggedInUser' => $this->getLoggedInUser()));
	}
}
